package com.ymatou.iapi.sellerproduct.testcase;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.ymatou.iapi.sellerproduct.parameter.ProdTplBean;
import com.ymatou.iapi.sellerproduct.service.AddFbxProductCall;
import com.ymatou.iapi.sellerproduct.service.AddNewSellerProductCall;
import com.ymatou.iapi.sellerproduct.service.SaveProductTemplateCall;
import com.ymt.core.tool.Logger;
import com.ymt.utils.annotation.TestCase;
import com.ymt.utils.annotation.TestSuite;
import com.ymt.utils.tag.P1;
import com.ymttest.business.service.NewJavaMongoCheckService;
import com.ymttest.business.service.SellerProductCallService;
import com.ymttest.database.mongo.YmtMongoDriverFactroy;
import com.ymttest.database.sqlwapper.YmtProductsIWapper;
import com.ymttest.utils.EnvSetup;
import com.ymttest.utils.YMTDateUtil;
/**
*添加长期售卖商品
*FreeMaker Template自动生成代码
*/
@TestSuite
public class Ts_AddFbxProduct{
	private static AddFbxProductCall addFbxProductCall;
	private static AddNewSellerProductCall addnewsellerproductCall;
	private static Integer sellerId = Integer.valueOf(EnvSetup.getData("productsellerid"));
	private static String sellerName = EnvSetup.getData("productsellername");
	
	@BeforeClass
	public static void setUp() {
		Logger.createResultFile("添加长期售卖商品");
	}

	@Before
	public void caseUp() {
		addFbxProductCall=new AddFbxProductCall();
		addnewsellerproductCall=new AddNewSellerProductCall();	
	}
	
	@AfterClass
	public static void tearDown() {
		Logger.generateResult(addFbxProductCall.getOpurl());
	}
	
	
	/**
	 * 返回信息公用错误信息部分断言（正向Case场景）
	 * @param dataStr 传入报文信息
	 * @throws Exception 错误信息
	 * @return 商品ID
	 */
	public static String AddFbxProductreturncode(JSONObject dataStr) throws Exception {
	    try {	    	
			//返回报文断言		
			String code =  dataStr.getString("Code");
			Logger.verifyIsContains(200, code, "\"Code\":200");
			String bCode =  dataStr.getString("BCode");
			Logger.verifyIsContains(0, bCode, "\"BCode\":200");
			String msg =  dataStr.getString("Msg");
			Logger.verifyIsNull(msg, "Msg等于空");		
			String trace =  dataStr.getString("Trace");
			Logger.verifyIsNull(trace, "Trace等于空");
			String sProductID =  dataStr.getJSONObject("Data").getString("ProductID");
			Logger.verifyNotNull(sProductID, "商品id不能为空");
			
	    	return  sProductID; 	    	
	    }catch (Exception e) {  
	        e.printStackTrace();
	    }  
	    return "";
	}	
	
	@After
	public void caseDown() {
		Logger.end();
	}
	
		

	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_AddFbxProduct_001() {
		Logger.start(true,"添加FBX商品（单规格）");
		try {
			//TODO 补全case代码			
			Map<String, Object> calldate = addProduct001();
			//发布FBX商品
			JSONObject result = addFbxProductCall.addFBXProductOneCatalog(calldate);
			JSONObject jsonBeanRequest = result.getJSONObject("JsonBeanRequest");
			//返回报文断言并取出ProductId
			String productID = AddFbxProductreturncode(result);
			String sSKU=jsonBeanRequest.getJSONObject("Product").getJSONArray("Catalogs").getJSONObject(0).getString("SKU");
			//SQL Mango断言
			addnewsellerproductCall.checkNewProduct(jsonBeanRequest, productID);	
			addnewsellerproductCall.checkCatalogsprice(jsonBeanRequest, productID);
			
			if (YmtMongoDriverFactroy.isNewMongoCheck()){	
			//新Mongo断言
				addnewsellerproductCall.checkNewMongoProductModel(result, productID, sellerId);
			}
			
			//订阅表
	    	YmtProductsIWapper ymtProductsIWapper = new YmtProductsIWapper();
	        List<Map> rm = ymtProductsIWapper.selectSubscribeRecord(3383,sSKU);
	        if (rm == null || rm.size()==0) {
	        	Logger.debug("BUG,没有写入库存订阅表");
			} else {
				int iOperationType = (int) rm.get(0).get("iOperationType");
		        Logger.verifyEquals(1, iOperationType, "SQL订阅库存表记录对比");
			}	        	        
	        
	        if (YmtMongoDriverFactroy.IsNewJavaMongoOpen){
				NewJavaMongoCheckService.checkProductMgoSyncBySQL_NewJavaMgo(productID);
			}
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_AddFbxProduct_002() {
		Logger.start(true,"添加FBX商品（双规格）");
		try {
			//TODO 补全case代码			
			Map<String, Object> calldate = addProduct001();
			//发布FBX商品
			JSONObject result = addFbxProductCall.addFBXProductTwoCatalog(calldate);
			JSONObject jsonBeanRequest = result.getJSONObject("JsonBeanRequest");
			//返回报文断言并取出ProductId
			String productID = AddFbxProductreturncode(result);
			String sSKU1=jsonBeanRequest.getJSONObject("Product").getJSONArray("Catalogs").getJSONObject(0).getString("SKU");
			String sSKU2=jsonBeanRequest.getJSONObject("Product").getJSONArray("Catalogs").getJSONObject(1).getString("SKU");
			//SQL Mango断言
			addnewsellerproductCall.checkNewProduct(jsonBeanRequest, productID);	
			addnewsellerproductCall.checkCatalogsprice(jsonBeanRequest, productID);
			
			if (YmtMongoDriverFactroy.isNewMongoCheck()){	
			//新Mongo断言
				addnewsellerproductCall.checkNewMongoProductModel(result, productID, sellerId);
			}
			
			//订阅表
	    	YmtProductsIWapper ymtProductsIWapper = new YmtProductsIWapper();
	        List<Map> rm = ymtProductsIWapper.selectSubscribeRecord(3383,sSKU1);
	        if (rm == null || rm.size()==0) {
	        	Logger.debug("BUG,没有写入库存订阅表");
			} else {
				int iOperationType = (int) rm.get(0).get("iOperationType");
		        Logger.verifyEquals(1, iOperationType, "SQL订阅库存表记录对比");
			}	        	        
	        
	        List<Map> rm2 = ymtProductsIWapper.selectSubscribeRecord(3383,sSKU2);
	        if (rm2 == null || rm2.size()==0) {
	        	Logger.debug("BUG,没有写入库存订阅表");
			} else {
				int iOperationType = (int) rm2.get(0).get("iOperationType");
		        Logger.verifyEquals(1, iOperationType, "SQL订阅库存表记录对比");
			}
	        
	        if (YmtMongoDriverFactroy.IsNewJavaMongoOpen){
				NewJavaMongoCheckService.checkProductMgoSyncBySQL_NewJavaMgo(productID);
			}
		} catch (Exception e) {
			Logger.fail(e);
		}
	}	
	
	
	
	
	
	/**
	 * 新品逻辑脚线部分
	 * ------------------------------------------------------------------
	 */
	
	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_AddFbxProduct_020() {
		Logger.start(true,"FBX立即上架商品 - 校验新品露出时间");
		try {
			//TODO 补全case代码			
			String productname ="(假)自动化FBX商品X"+ YMTDateUtil.getSysTime();			
			Map<String, Object> calldate = new HashMap<String, Object>();
			calldate.put("UserID", 3383);
			calldate.put("LoginID", "wesper");
			calldate.put("Product->ProductName", productname);
			calldate.put("Product->IsNew", true);
			//发布FBX商品
			JSONObject result = addFbxProductCall.addFBXProductOneCatalog(calldate);
			JSONObject jsonBeanRequest = result.getJSONObject("JsonBeanRequest");
						
			//返回报文断言并取出ProductId
			String productID = AddFbxProductreturncode(result);
			String sSKU=jsonBeanRequest.getJSONObject("Product").getJSONArray("Catalogs").getJSONObject(0).getString("SKU");
			
			
			//首次露出时间、结束时间断言
			SellerProductCallService.checkSqlListingTime(productID, 1);
			SellerProductCallService.checkListingTime(productID, null);			
			 if (YmtMongoDriverFactroy.IsNewJavaMongoOpen){
					NewJavaMongoCheckService.checkProductMgoSyncBySQL_NewJavaMgo(productID);
				}			
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	
	
	
	
	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_AddFbxProduct_021() {
		Logger.start(true,"PC发布直播商品  属性 模板");
		try {
			SaveProductTemplateCall saveProductTemplateCall = new SaveProductTemplateCall();
			
			//	模版类型（1，尺码模版 2，买家须知 3，买手服务）
			saveProductTemplateCall.deleteTemplate(sellerId);
			//	模版类型（1，尺码模版 2，买家须知 3，买手服务）
			ProdTplBean sizeTemplate = saveProductTemplateCall.saveTemplate(sellerId, 1);
			ProdTplBean buyerNoticeTemplate = saveProductTemplateCall.saveTemplate(sellerId, 2);
			ProdTplBean sellerServiceTemplate = saveProductTemplateCall.saveTemplate(sellerId, 3);
			
			Map<String, Object> thirdCategoryAndPropertyVal = SellerProductCallService.getThirdCategoryAndPropertyValue();
			
			//TODO 补全case代码			
			String productname ="(假)自动化FBX商品X"+ YMTDateUtil.getSysTime();			
			Map<String, Object> calldate = new HashMap<String, Object>();
			calldate.put("UserID", sellerId);
			calldate.put("LoginID", sellerName);
			calldate.put("Product->ProductName", productname);
			calldate.put("Product->iThirdCategoryId", thirdCategoryAndPropertyVal.get("ThirdCategory"));
			calldate.put("Product->PropertyList", (JSONArray)thirdCategoryAndPropertyVal.get("PropertyList"));
			calldate.put("Product->SizeTemplateId", sizeTemplate.getTemplateId());
			calldate.put("Product->BuyerNoticeId",buyerNoticeTemplate.getTemplateId());
			calldate.put("Product->SellerServiceId", sellerServiceTemplate.getTemplateId());	
		
			
			//发布FBX商品
			JSONObject result = AddFbxProductCall.addFBXProductOneCatalog(calldate);
			//返回报文断言并取出ProductId
			String productId = AddFbxProductreturncode(result);
			
			//属性检查
			SellerProductCallService.checkProdProperty(productId,(JSONArray)thirdCategoryAndPropertyVal.get("PropertyList"));
			
			//模板检查
			//check product template
			SellerProductCallService.checkTemplateWithProd(productId, Arrays.asList(sizeTemplate,buyerNoticeTemplate,sellerServiceTemplate));
			
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	
	
	/**
	 * ------------------------------------------------------------------
	 */
	
	
	/**
	 * 新增商品case001
	 * @return calldate
	 * @throws Exception
	 */
	public static Map<String, Object> addProduct001() throws Exception {
		try {			
			String productname ="(假)自动化FBX商品X"+ YMTDateUtil.getSysTime();
			String mobileDescription ="FBX商品介绍X"+ YMTDateUtil.getSysTime();
			String picturl="http://pm1.img.ymatou.com/G01/upload/product/original/M00/15/F0/rBBlD1dwky2AOhI6AAAphnmT5Z0419_n_w_o.jpg";
			String wordContent ="FBX商品文字描述X"+ YMTDateUtil.getSysTime();
			String description ="FBX老商品详情描述X"+ YMTDateUtil.getSysTime();
			BigDecimal price = new BigDecimal((int)(Math.random()*1000)+3); 
			BigDecimal vipprice = price.subtract(new BigDecimal("1"));
			BigDecimal newcustomerprice = price.subtract(new BigDecimal("2"));
			int num = (int)(Math.random()*10000);
			String sSKU="FBXSKU"+num;
			String sProductCode="FBXProductCode"+num;
			boolean limited = true;
			int limitnum= (int)(Math.random()*10);
			String limitNumStartTime = YMTDateUtil.getSysTime();	//限购开始时间
			boolean noticeRisk = false;	//砍单风险
			int tariffType = 1; //1不包税 0包税
			int onSaleType = 0; //立即上架 
			int localReturn = 1; //1官方退货 2买手本土退货
			boolean noReasonReturn = false; //无理由退货
			int iCategoryId = 1191; 	//商品类目
			int iThirdCategoryId = 1194; 	//三级类目
			int iBrandId = 10098; 	//品牌ID

			List<String> aapicurl=new ArrayList<>();
			aapicurl.add(picturl);
			aapicurl.add(picturl);
			Map<String, Object> calldate = new HashMap<String, Object>();
			calldate.put("UserID", 3383);
			calldate.put("LoginID", "wesper");
			calldate.put("Product->ProductName", productname);
			calldate.put("Product->MobileDescription", mobileDescription);
			calldate.put("Product->PictureUrl1", picturl);
			calldate.put("Product->PictureUrl2", picturl);
			calldate.put("Product->ProductPics", new JSONArray(aapicurl));
//			calldate.put("Product->ProductDescriptionInfo->Pictures[0]->PictureUrl",picturl);
			calldate.put("Product->ProductDescriptionInfo->WordContent", wordContent);
			calldate.put("Product->Catalogs[0]->Price", price);
			calldate.put("Product->Catalogs[0]->VipPrice", vipprice);
			calldate.put("Product->Catalogs[0]->NewCustomerPrice", newcustomerprice);
			calldate.put("Product->Catalogs[0]->Num", num);
			calldate.put("Product->Catalogs[0]->SKU", sSKU);
			calldate.put("Product->Catalogs[0]->ProductCode", sProductCode);
//			calldate.put("Product->ProductCode", sProductCode);
			calldate.put("Product->Limited", limited);
			calldate.put("Product->LimitNum", limitnum);
			calldate.put("Product->LimitNumStartTime", limitNumStartTime);
			calldate.put("Product->NoticeRisk", noticeRisk);
			calldate.put("Product->TariffType", tariffType);
			calldate.put("Product->OnSaleType", onSaleType);
			calldate.put("Product->LocalReturn", localReturn);
			calldate.put("Product->NoReasonReturn", noReasonReturn);
			calldate.put("Product->iCategoryId", iCategoryId);
			calldate.put("Product->iThirdCategoryId", iThirdCategoryId);
			calldate.put("Product->iBrandId", iBrandId);
			calldate.put("Product->Description",description);
			
			return calldate;
		} catch (Exception e) {   
			e.printStackTrace();
		}
		return null;	
	}		
	
	
}